package cn.lblbc.webbrowser

import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.cardview.widget.CardView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import cn.lblbc.webbrowser.adapters.ImageGridAdapter
import cn.lblbc.webbrowser.utils.ImageCollectionSettings
import cn.lblbc.webbrowser.utils.ImageCollector
import java.io.File

class CollectedImagesActivity : BaseActivity() {
    
    private lateinit var recyclerView: RecyclerView
    private lateinit var imageCollector: ImageCollector
    private lateinit var adapter: ImageGridAdapter
    private lateinit var imageCollectionSettings: ImageCollectionSettings
    
    // 批量操作相关UI
    private lateinit var selectionToolbar: LinearLayout
    private lateinit var selectionCountText: TextView
    private lateinit var selectAllButton: ImageButton
    private lateinit var deleteSelectedButton: ImageButton
    private lateinit var cancelSelectionButton: ImageButton
    
    // 空状态相关UI
    private lateinit var emptyStateLayout: LinearLayout
    private lateinit var emptyStateIcon: ImageView
    private lateinit var emptyStateTitle: TextView
    private lateinit var emptyStateMessage: TextView
    private lateinit var settingsCard: CardView
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_collected_images)
        
        initViews()
        imageCollector = ImageCollector(this)
        imageCollectionSettings = ImageCollectionSettings(this)
        setupRecyclerView()
        setupListeners()
        loadImages()
    }
    
    private fun initViews() {
        recyclerView = findViewById(R.id.imagesRecyclerView)
        selectionToolbar = findViewById(R.id.selectionToolbar)
        selectionCountText = findViewById(R.id.selectionCountText)
        selectAllButton = findViewById(R.id.selectAllButton)
        deleteSelectedButton = findViewById(R.id.deleteSelectedButton)
        cancelSelectionButton = findViewById(R.id.cancelSelectionButton)
        
        // 空状态视图
        emptyStateLayout = findViewById(R.id.emptyStateLayout)
        emptyStateIcon = findViewById(R.id.emptyStateIcon)
        emptyStateTitle = findViewById(R.id.emptyStateTitle)
        emptyStateMessage = findViewById(R.id.emptyStateMessage)
        settingsCard = findViewById(R.id.settingsCard)
    }
    
    private fun setupListeners() {
        // 设置返回按钮
        findViewById<ImageButton>(R.id.backButton)?.setOnClickListener {
            if (adapter.isInSelectionMode()) {
                exitSelectionMode()
            } else {
                finish()
            }
        }
        
        // 设置清除所有按钮
        findViewById<ImageButton>(R.id.clearButton)?.setOnClickListener {
            showClearAllConfirmation()
        }
        
        // 全选/全不选按钮
        selectAllButton.setOnClickListener {
            if (adapter.areAllSelected()) {
                adapter.clearSelection()
            } else {
                adapter.selectAll()
            }
        }
        
        // 删除选中按钮
        deleteSelectedButton.setOnClickListener {
            deleteSelectedImages()
        }
        
        // 取消选择按钮
        cancelSelectionButton.setOnClickListener {
            exitSelectionMode()
        }
        
        // 设置卡片点击事件
        settingsCard.setOnClickListener {
            startActivity(Intent(this, SettingsActivity::class.java))
        }
    }
    
    private fun setupRecyclerView() {
        recyclerView.layoutManager = GridLayoutManager(this, 3)
        adapter = ImageGridAdapter(
            onImageClick = { imageFile ->
                // 点击图片时跳转到全屏查看
                showFullscreenImage(imageFile)
            },
            onImageLongClick = { imageFile ->
                // 长按进入选择模式
                enterSelectionMode()
            },
            onSelectionChanged = { count ->
                // 选择数量变化时更新UI
                updateSelectionUI(count)
            }
        )
        recyclerView.adapter = adapter
    }
    
    private fun loadImages() {
        try {
            val images = imageCollector.getCollectedImages()
            adapter.updateImages(images)
            updateEmptyState(images.isEmpty())
        } catch (e: Exception) {
            e.printStackTrace()
            updateEmptyState(true)
        }
    }
    
    private fun updateEmptyState(isEmpty: Boolean) {
        if (isEmpty) {
            recyclerView.visibility = View.GONE
            emptyStateLayout.visibility = View.VISIBLE
            
            // 检查图片收集是否开启
            if (!imageCollectionSettings.isEnabled) {
                // 图片收集已关闭
                emptyStateIcon.setImageResource(R.drawable.ic_settings)
                emptyStateTitle.text = getString(R.string.collection_disabled_title)
                emptyStateMessage.text = getString(R.string.collection_disabled_message)
                settingsCard.visibility = View.VISIBLE
            } else {
                // 图片收集已开启，但没有图片
                emptyStateIcon.setImageResource(R.drawable.ic_image)
                emptyStateTitle.text = getString(R.string.no_collected_images)
                emptyStateMessage.text = getString(R.string.no_collected_images_message)
                settingsCard.visibility = View.GONE
            }
        } else {
            recyclerView.visibility = View.VISIBLE
            emptyStateLayout.visibility = View.GONE
        }
    }
    
    private fun showFullscreenImage(imageFile: File) {
        try {
            val allImages = imageCollector.getCollectedImages()
            val currentPosition = allImages.indexOf(imageFile)
            
            if (currentPosition >= 0) {
                val intent = Intent(this, ImageViewerActivity::class.java)
                intent.putExtra("image_files", ArrayList(allImages))
                intent.putExtra("current_position", currentPosition)
                startActivity(intent)
            }
        } catch (e: Exception) {
            e.printStackTrace()
            Toast.makeText(this, "无法打开图片查看器", Toast.LENGTH_SHORT).show()
        }
    }
    
    private fun enterSelectionMode() {
        adapter.enterSelectionMode()
        selectionToolbar.visibility = View.VISIBLE
        updateSelectionUI(0)
    }
    
    private fun exitSelectionMode() {
        adapter.exitSelectionMode()
        selectionToolbar.visibility = View.GONE
    }
    
    private fun updateSelectionUI(selectedCount: Int) {
        selectionCountText.text = getString(R.string.selected_count, selectedCount)
        deleteSelectedButton.isEnabled = selectedCount > 0
        deleteSelectedButton.alpha = if (selectedCount > 0) 1.0f else 0.5f
        
        // 更新全选按钮状态
        if (adapter.areAllSelected()) {
            selectAllButton.setImageResource(R.drawable.ic_select_none)
            selectAllButton.contentDescription = "全部不选"
        } else {
            selectAllButton.setImageResource(R.drawable.ic_select_all)
            selectAllButton.contentDescription = "全选"
        }
    }
    
    private fun deleteSelectedImages() {
        val selectedImages = adapter.getSelectedImages()
        if (selectedImages.isEmpty()) {
            Toast.makeText(this, getString(R.string.please_select_images), Toast.LENGTH_SHORT).show()
            return
        }
        
        AlertDialog.Builder(this)
            .setTitle(R.string.delete_images_title)
            .setMessage(getString(R.string.delete_images_message, selectedImages.size))
            .setPositiveButton("删除") { _, _ ->
                performDeleteSelectedImages(selectedImages)
            }
            .setNegativeButton("取消", null)
            .show()
    }
    
    private fun performDeleteSelectedImages(imagesToDelete: List<File>) {
        try {
            var deletedCount = 0
            imagesToDelete.forEach { file ->
                if (file.exists() && file.delete()) {
                    deletedCount++
                }
            }
            
            exitSelectionMode()
            loadImages()
            
            Toast.makeText(this, getString(R.string.images_deleted, deletedCount), Toast.LENGTH_SHORT).show()
            
        } catch (e: Exception) {
            e.printStackTrace()
            Toast.makeText(this, "删除失败: ${e.message}", Toast.LENGTH_SHORT).show()
        }
    }
    
    private fun showClearAllConfirmation() {
        val totalCount = imageCollector.getCollectedImages().size
        if (totalCount == 0) {
            Toast.makeText(this, getString(R.string.no_images_to_clear), Toast.LENGTH_SHORT).show()
            return
        }
        
        AlertDialog.Builder(this)
            .setTitle(R.string.clear_all_images_title)
            .setMessage(getString(R.string.clear_all_images_message, totalCount))
            .setPositiveButton("清除") { _, _ ->
                clearAllImages()
            }
            .setNegativeButton("取消", null)
            .show()
    }
    
    private fun clearAllImages() {
        try {
            val deletedCount = imageCollector.clearAllImages()
            loadImages()
            Toast.makeText(this, getString(R.string.images_cleared, deletedCount), Toast.LENGTH_SHORT).show()
        } catch (e: Exception) {
            e.printStackTrace()
            Toast.makeText(this, "清除图片失败: ${e.message}", Toast.LENGTH_SHORT).show()
        }
    }
    
    override fun onResume() {
        super.onResume()
        // 每次显示时重新加载图片
        loadImages()
    }
    
    @Deprecated("Deprecated in Java")
    override fun onBackPressed() {
        if (adapter.isInSelectionMode()) {
            exitSelectionMode()
        } else {
            super.onBackPressed()
        }
    }
}
    